#include "Conectfd.h"
// enum class State;
Connectfd::Connectfd(int fd_, EpollLoop *eploop, State st) : fd(fd_),
                                                             m_state(st), m_epollLoop(eploop)
{
    strRead.reserve(BUFFER_LENGTH);
    strWrite.reserve(BUFFER_LENGTH);
}
Connectfd::~Connectfd()
{
    if (fd >= 0)
        close(fd);
}

void Connectfd::handelEvent(uint32_t events)
{
    if (events & EPOLLIN)
    {
        if (m_state == State::ACCEPTING)
        {
            handelAccept();
        }
        else
        {
            handelRead();
        }
    }
    if (events & EPOLLOUT)
    {
        handelWrite();
    }
}
Connectfd::State Connectfd::state()
{
    return m_state;
}

int Connectfd::fdVal()
{
    return fd;
}

void Connectfd::handelAccept()
{
    sockaddr_in addr;
    socklen_t len = sizeof(addr);
    int client = accept(fd, (sockaddr *)&addr, &len);
    m_epollLoop->addConnectClient(client, EPOLLIN);
}

void Connectfd::handelRead()
{
    strRead.clear();
    char buff[BUFFER_LENGTH];
    int count = read(fd, (void *)buff, BUFFER_LENGTH);
    if (count <= 0)
    {
        m_state = State::CLOSE;
        return;
    }
    strRead.append(buff, count);
    printf("read:__fd: %d, Readbuffer:%s\n", fd, strRead.c_str());
    strWrite = strRead;
    m_state = State::WRITEING;
}

void Connectfd::handelWrite()
{
    ssize_t r = send(fd, strWrite.c_str() + m_pos, strWrite.size() - m_pos, 0);
    if (r <= 0)
    {
        m_state = State::CLOSE;
        return;
    }
    m_pos += r;
    if (m_pos >= strWrite.size())
    {
        m_pos = 0;
        strWrite.clear();
        m_state = State::READING;
    }
}
